package com.yhd.service.impl;

import com.github.pagehelper.Page;
import com.yhd.entity.TCourse;
import com.yhd.entity.TCourseBooked;
import com.yhd.entity.TUser;
import com.yhd.entity.dto.CourseBookedDto;
import com.yhd.entity.dto.CourseDto;
import com.yhd.entity.dto.UserDto;
import com.yhd.entity.query.CourseBookedVO;
import com.yhd.entity.result.ResultVo;
import com.yhd.mapper.CourseBookedMapper;
import com.yhd.mapper.CourseMapper;
import com.yhd.mapper.UserMapper;
import com.yhd.model.PageInfo;
import com.yhd.model.ResultPage;
import com.yhd.service.BaseService;
import com.yhd.service.CourseBookedService;
import com.yhd.utils.BeanMapperUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class CourseBookedServiceImpl extends BaseService<CourseBookedMapper, TCourseBooked> implements CourseBookedService {
	@Autowired
	private CourseBookedMapper courseBookedMapper;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private UserMapper userMapper;

	@Override
	public Integer getCourseBookeCount(Integer courseId, String userId) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("courseId", courseId)
				.andNotEqualTo("status", 3);
		if (!StringUtils.isEmpty(userId)) {
			criteria.andEqualTo("cuserId", userId);
		}
		return courseBookedMapper.selectCountByExample(example);
	}

	@Override
	public CourseBookedDto getUserCourseBooke(Integer courseId, String userId) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("courseId", courseId)
				.andNotIn("status", Arrays.asList(3, 4));//不查拒绝和取消的
		criteria.andEqualTo("cuserId", userId);
		criteria.andEqualTo("participate", 1);
		List<TCourseBooked> bookeds = courseBookedMapper.selectByExample(example);
		if (!CollectionUtils.isEmpty(bookeds)) {
			TCourseBooked booked = bookeds.get(0);
			CourseBookedDto bookedDto = new CourseBookedDto();
			BeanUtils.copyProperties(booked, bookedDto);
			return bookedDto;
		}
		return null;
	}

	@Override
	public CourseBookedDto getUserCourseSuccessBooke(Integer courseId, String userId) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("courseId", courseId);
		criteria.andEqualTo("cuserId", userId);
		criteria.andEqualTo("participate", 1);
		criteria.andEqualTo("status", 2);
		criteria.andNotEqualTo("subType", 1);
		List<TCourseBooked> bookeds = courseBookedMapper.selectByExample(example);
		if (!CollectionUtils.isEmpty(bookeds)) {
			TCourseBooked booked = bookeds.get(0);
			CourseBookedDto bookedDto = new CourseBookedDto();
			BeanUtils.copyProperties(booked, bookedDto);
			return bookedDto;
		}
		return null;
	}

	
	@Override
	public CourseBookedDto getUserCourseBookeSubType(Integer courseId, String userId) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("courseId", courseId)
				.andNotIn("status", Arrays.asList(3, 4));//不查拒绝和取消的
		criteria.andEqualTo("cuserId", userId);
		criteria.andEqualTo("participate", 1);
		criteria.andEqualTo("subType", 0);
		List<TCourseBooked> bookeds = courseBookedMapper.selectByExample(example);
		if (!CollectionUtils.isEmpty(bookeds)) {
			TCourseBooked booked = bookeds.get(0);
			CourseBookedDto bookedDto = new CourseBookedDto();
			BeanUtils.copyProperties(booked, bookedDto);
			return bookedDto;
		}
		return null;
	}
	
	
	@Override
	public Integer getUserFreeBookeCount(String userId) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria()
				.andNotEqualTo("status", 3).andEqualTo("subType", 1);
		criteria.andEqualTo("cuserId", userId);
		return courseBookedMapper.selectCountByExample(example);
	}
	
	@Override
	public TCourseBooked selectBookeByOrderNo(String orderNo) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria()
				.andEqualTo("status", 1);
		criteria.andEqualTo("orderNo", orderNo);
		return courseBookedMapper.selectOneByExample(example);
	}

	@Override
	public void update(TCourseBooked courseBooked) {
		this.updateByPrimaryKeySelective(courseBooked);
	}
	
	@Override
	public TCourseBooked selectById(Integer orderId) {
		if (orderId == null) {
			return null;
		}
		TCourseBooked booked = new TCourseBooked();
		booked.setId(orderId);
		return this.selectOne(booked);
	}
	
	@Override
	public List<CourseBookedDto> userOrderList(String type, Integer status, String userId) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("cuserId", userId);
		if (!StringUtils.isEmpty(type)) {
			criteria.andEqualTo("type",type);
		}

		if (status != null) {
			criteria.andEqualTo("status",status);
		}
		example.setOrderByClause("createTime desc");
		List<TCourseBooked> select = this.selectByExample(example);
		return BeanMapperUtil.copyList(select, CourseBookedDto.class);
	}
	
	/**
	 * 取消订单
	 * @param bookedVO
	 * @param userInfo
	 * @return
	 */
	@Override
	public CourseBookedDto cancelOrder(CourseBookedVO bookedVO, UserDto userInfo) {
		TCourseBooked booked = new TCourseBooked();
		BeanUtils.copyProperties(bookedVO, booked);
		booked.setStatus(4);
		booked.setUpdateTime(new Date());
		this.updateByPrimaryKeySelective(booked);
		
		booked = new TCourseBooked();
		booked.setId(bookedVO.getId());
		
		booked = this.selectOne(booked);
		
		CourseBookedDto result = new CourseBookedDto();
		BeanUtils.copyProperties(booked, result);
		return result;
	}
	
	@Override
	public List<TCourseBooked> getUserCourseBookeList(String userId, Integer status) {
		Example example = new Example(TCourseBooked.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("cuserId", userId);
		if (status != null) {
			criteria.andEqualTo("status", status);
		}
		criteria.andEqualTo("participate", 1);
		example.setOrderByClause("createTime desc");
		return courseBookedMapper.selectByExample(example);
	}

	@Override
	public ResultPage<List<CourseBookedDto>> selectCourseBookedList(CourseBookedVO courseBookedVO) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(courseBookedVO.getPageNum());
		pageInfo.setPageSize(courseBookedVO.getPageSize());
		Page<List<CourseBookedDto>> reslut = pageBuild(pageInfo).doSelectPage(()->{
			List<CourseBookedDto> list = courseBookedMapper.selectCourseBookedList(courseBookedVO);
			for (CourseBookedDto courseBookedDto:list) {
				if (null != courseBookedDto.getCourseId()){
					TCourse tCourse = new TCourse();
					tCourse.setId(Integer.parseInt(courseBookedDto.getCourseId()));
					TCourse newTCourse = courseMapper.selectOne(tCourse);
					if (null != newTCourse){
						CourseDto courseDto = new CourseDto();
						BeanUtils.copyProperties(newTCourse,courseDto);
						courseBookedDto.setCourseDto(courseDto);
					}
				}
				if (null != courseBookedDto.getCuserId()){
					TUser tUser = new TUser();
					tUser.setId(courseBookedDto.getCuserId());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setUserDto(userDto);
					}
				}
				if (null != courseBookedDto.getReferrerUser()){
					TUser tUser = new TUser();
					tUser.setInvitationCode(courseBookedDto.getReferrerUser());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setReUserDto(userDto);
					}
				}
			}
		});
		return pageTransform(reslut);
	}

	@Override
	public CourseBookedDto selectCourseBookedInfo(CourseBookedVO courseBookedVO) {
		if (null != courseBookedVO && null != courseBookedVO.getId()){
			TCourseBooked tCourseBooked = new TCourseBooked();
			tCourseBooked.setId(courseBookedVO.getId());
			TCourseBooked newTCourseBooked = courseBookedMapper.selectOne(tCourseBooked);
			if (null != newTCourseBooked){
				CourseBookedDto courseBookedDto = new CourseBookedDto();
				BeanUtils.copyProperties(newTCourseBooked,courseBookedDto);
				if (null != courseBookedDto.getCourseId()){
					TCourse tCourse = new TCourse();
					tCourse.setId(Integer.parseInt(courseBookedDto.getCourseId()));
					TCourse newTCourse = courseMapper.selectOne(tCourse);
					if (null != newTCourse){
						CourseDto courseDto = new CourseDto();
						BeanUtils.copyProperties(newTCourse,courseDto);
						courseBookedDto.setCourseDto(courseDto);
					}
				}
				if (null != courseBookedDto.getCuserId()){
					TUser tUser = new TUser();
					tUser.setId(courseBookedDto.getCuserId());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setUserDto(userDto);
					}
				}
				if (null != courseBookedDto.getReferrerUser()){
					TUser tUser = new TUser();
					tUser.setInvitationCode(courseBookedDto.getReferrerUser());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setReUserDto(userDto);
					}
				}
				return courseBookedDto;
			}
		}
		return null;
	}

	@Override
	public ResultVo<CourseBookedDto> putCourseBooked(CourseBookedVO courseBookedVO, UserDto userInfo) {
		if (null != courseBookedVO && null != courseBookedVO.getId()){
			TCourseBooked tCourseBooked = new TCourseBooked();
			BeanUtils.copyProperties(courseBookedVO,tCourseBooked);
			if (null != courseBookedVO && null != courseBookedVO.getPayType() && courseBookedVO.getPayType()== 0){
				//线下支付及完成支付
				tCourseBooked.setStatus(2);
				tCourseBooked.setPayTime(new Date());
			}
			if (null != courseBookedVO && null != courseBookedVO.getPayType() && courseBookedVO.getPayType()== 1){
				//线上支付及1:待付款
				tCourseBooked.setStatus(1);
			}
			tCourseBooked.setUpdateTime(new Date());
			tCourseBooked.setUpdateUserId(userInfo.getId());
			TCourseBooked newCourseBooked = new TCourseBooked();
			newCourseBooked.setId(courseBookedVO.getId());
			TCourseBooked pCourseBooked = courseBookedMapper.selectOne(newCourseBooked);
			if (null != courseBookedVO.getParticipate() && null != pCourseBooked){
				if (null != pCourseBooked && pCourseBooked.getStatus() != 2){
					//必须是已付款订单才能设置是否允许继续参与
					return ResultVo.failure("10009","该订单必须已支付！");
				}
			}
			int updateOrder = courseBookedMapper.updateByPrimaryKeySelective(tCourseBooked);
			if (updateOrder > 0){
				//拒绝退库存及减销量
				if (null != courseBookedVO.getParticipate() && courseBookedVO.getParticipate() == 0){
					TCourseBooked tCourseBooked1 = new TCourseBooked();
					tCourseBooked1.setId(courseBookedVO.getId());
					TCourseBooked newTCourseBooked1 = courseBookedMapper.selectOne(tCourseBooked1);
					if (null != newTCourseBooked1 && newTCourseBooked1.getSubType() != 1){
						TCourse tCourse = new TCourse();
						tCourse.setId(Integer.parseInt(newTCourseBooked1.getCourseId()));
						TCourse newTCourse = courseMapper.selectOne(tCourse);
						if (null != newTCourse){
							Integer saleNum = newTCourse.getSaleNum();
							if (saleNum > 0){
								newTCourse.setSaleNum(saleNum - 1);
								courseMapper.updateByPrimaryKeySelective(newTCourse);
							}
						}
					}
				}
				if (null != courseBookedVO && null != courseBookedVO.getPayType() && courseBookedVO.getPayType()== 0){
					//线下支付及完成支付
					//更新课程销售量
					if (null != pCourseBooked){
						TCourse course = new TCourse();
						course.setId(Integer.parseInt(pCourseBooked.getCourseId()));
						course = courseMapper.selectByPrimaryKey(course);
						course.setSaleNum(course.getSaleNum() + 1);
						courseMapper.updateByPrimaryKeySelective(course);
					}
				}
				CourseBookedDto courseBookedDto = new CourseBookedDto();
				BeanUtils.copyProperties(tCourseBooked,courseBookedDto);
				return ResultVo.success(courseBookedDto);
			}
		}
		return null;
	}

	/**
	 * 活动报名列表
	 * @param courseBookedVO
	 * @return
	 */
	@Override
	public ResultPage<List<CourseBookedDto>> selectActivityOrderList(CourseBookedVO courseBookedVO) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(courseBookedVO.getPageNum());
		pageInfo.setPageSize(courseBookedVO.getPageSize());
		Page<List<CourseBookedDto>> reslut = pageBuild(pageInfo).doSelectPage(()->{
			List<CourseBookedDto> list = courseBookedMapper.selectActivityOrderList(courseBookedVO);
			for (CourseBookedDto courseBookedDto:list) {
				if (null != courseBookedDto.getCuserId()){
					TUser tUser = new TUser();
					tUser.setId(courseBookedDto.getCuserId());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setUserDto(userDto);
					}
				}
				if (null != courseBookedDto.getReferrerUser()){
					TUser tUser = new TUser();
					tUser.setInvitationCode(courseBookedDto.getReferrerUser());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setReUserDto(userDto);
					}
				}
			}
		});
		return pageTransform(reslut);
	}

	@Override
	public ResultPage<List<CourseBookedDto>> selectCourseSchList(CourseBookedVO courseBookedVO) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(courseBookedVO.getPageNum());
		pageInfo.setPageSize(courseBookedVO.getPageSize());
		Page<List<CourseBookedDto>> reslut = pageBuild(pageInfo).doSelectPage(()->{
			List<CourseBookedDto> list = courseBookedMapper.selectCourseSchList(courseBookedVO);
			for (CourseBookedDto courseBookedDto:list) {
				//预约状态：0未预约 1学员约课 2免费体验
				if (courseBookedDto.getSubType() == 1){
					courseBookedDto.setSchStatus(2);
				}else {
					int courseSchNum = courseBookedMapper.getCourseSchNum(courseBookedDto.getId(),courseBookedDto.getCourseId(),courseBookedVO.getCourseSchId());
					if (courseSchNum > 0){
						courseBookedDto.setSchStatus(1);
					}else {
						courseBookedDto.setSchStatus(0);
					}
				}
				if (null != courseBookedDto.getCuserId()){
					TUser tUser = new TUser();
					tUser.setId(courseBookedDto.getCuserId());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setUserDto(userDto);
					}
				}
				if (null != courseBookedDto.getReferrerUser()){
					TUser tUser = new TUser();
					tUser.setInvitationCode(courseBookedDto.getReferrerUser());
					TUser newTUser = userMapper.selectOne(tUser);
					if (null != newTUser){
						UserDto userDto = new UserDto();
						BeanUtils.copyProperties(newTUser,userDto);
						courseBookedDto.setReUserDto(userDto);
					}
				}
			}
		});
		return pageTransform(reslut);
	}
}
